/**
 * 
 */
package co.fitstart.coach.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import co.fitstart.coach.service.MessageService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.principal.PrincipalMessage;

/**
 * @author mohanlan 
 */
@Controller
@RequestMapping("/messages")
public class MessageController {
    
    @Autowired
    private MessageService messageService;
    
    @Autowired
    private PrincipalService principalService;
    
    /**
     * List current month messages
     * 
     * @param id
     * @return
     */
    @RequestMapping("")
    public ModelAndView list(@Secure(property = "id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("message/message-list");
        
        Principal principal = principalService.load(Principal.class, id);
        
        //count current month unread message 
        int newMessageCount = messageService.countNewMessage(principal);
        List<PrincipalMessage> principalMessages = messageService.listMessages(principal);
        
        modelAndView.addObject("newMessageCount", newMessageCount);
        modelAndView.addObject("principalMessages", principalMessages);
        
        return modelAndView;
    }
    
    /**
     * view message detail and mark message as read
     * 
     * @param id
     * @return
     */
    @RequestMapping("/{id}")
    public ModelAndView view(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("message/message-view");

        PrincipalMessage principalMessage = messageService.load(PrincipalMessage.class, id);
        
        if (!principalMessage.isRead()) {
            messageService.updateMessageStatus(principalMessage);
        }
        
        modelAndView.addObject("principalMessage", principalMessage);
        
        return modelAndView;
    }

}
